//
//  ShufflingFigureView.swift
//  NetWork
//
//  Created by Delin Meng 孟德林 on 2018/10/30.
//  Copyright © 2018 Delin Meng 孟德林. All rights reserved.
//

import UIKit
import SnapKit


open class ShufflingFigureView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        configureUI()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        configureUI()
    }

    /// 轮播图
    private var collectionView:UICollectionView = {
        let collectView = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: ShufflingFigureLayout())
        return collectView
    }()

    /// 底部轮播视图
    private var shufflingFigureIdentifyView:ShufflingFigureIdentifyView = {
        let view = ShufflingFigureIdentifyView.init(frame: CGRect.zero)
        return view
    }()


    private func configureUI() {

        collectionView.dataSource = self
        collectionView.delegate = self

        collectionView.register(ShufflingFigureCell.self, forCellWithReuseIdentifier: ShufflingFigureComment.CellIdentifier)
        addSubview(collectionView)
        addSubview(shufflingFigureIdentifyView)

    }

    private var timer:Timer?
    private var urls:[String] = [String]()
    private var currentPage:Int = 0

    // --------------------------   对外接口

    // 自动隐藏只有一个的情况
    public var hidesForSinglePage:Bool = true


    // 设置数据源
    public func setDataSources(urls:[String],currentPage:Int) {
        self.urls = urls
        self.currentPage = currentPage
        collectionView.reloadData()
        let index = min(currentPage, urls.count)
        shufflingFigureIdentifyView.numberOfPages = urls.count
        if urls.count > 1 {
            DispatchQueue.main.async {
                let indexPath = IndexPath.init(item: index, section: 0)
                self.collectionView.scrollToItem(at: indexPath, at: .left, animated: false)
                self.shufflingFigureIdentifyView.currentPage = index
            }
        }else{

            if hidesForSinglePage {
                shufflingFigureIdentifyView.removeFromSuperview()
            }
        }
        beginShufflingAnimation()
    }
    // ---------------------------

    private func beginShufflingAnimation() {
        if urls.count > 1 {
            if timer == nil {
                timer = Timer.scheduledTimer(timeInterval: 4, target: self, selector: #selector(repeatArticlesShow), userInfo: nil, repeats: true)
            }
        }
    }

    private func endShufflingAnimation() {
        timer?.invalidate()
        timer = nil
    }

    @objc private func repeatArticlesShow() {

        let column =  urls.count
        var offset = collectionView.contentOffset.x
        if column > 1 {
            offset += UIScreen.main.bounds.size.width

            UIView.animate(withDuration: 0.6) {
                self.collectionView.setContentOffset(CGPoint(x: offset, y: 0), animated: true)
            }
            var num = offset / UIScreen.main.bounds.size.width
            if num == 0 || num == CGFloat(collectionView.numberOfItems(inSection: 0) - 1) {
                num = CGFloat(urls.count - (num == 0 ? 0:1))
                self.collectionView.contentOffset = CGPoint(x: num * self.collectionView.bounds.size.width, y: 0)
            }
            shufflingFigureIdentifyView.currentPage = Int(num)
        }
    }

    override open func layoutSubviews() {
        super.layoutSubviews()
        collectionView.snp.makeConstraints { (make) in
            make.left.right.top.bottom.equalToSuperview()
        }
        let width = (81 / 375.0) * UIScreen.main.bounds.size.width
        shufflingFigureIdentifyView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-15)
            make.height.equalTo(2)
            make.width.equalTo(width)
        }
    }

    deinit {

        print(NSStringFromClass(ShufflingFigureView.self) + "释放了")
        timer = nil
        NotificationCenter.default.removeObserver(self)
    }

}

extension ShufflingFigureView:UICollectionViewDataSource,UICollectionViewDelegate {

    public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return bounds.size

    }

    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return urls.count * (urls.count == 1 ? 1 : 100)
    }

    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier:ShufflingFigureComment.CellIdentifier , for: indexPath) as! ShufflingFigureCell
        cell.setUrl(imageUrl: urls[indexPath.item % (urls.count)])
        return cell
    }


    ///  UISCrollView - Delegate

    public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        endShufflingAnimation()
    }

    public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {

            var offset = scrollView.contentOffset.x / UIScreen.main.bounds.size.width
            if offset == 0 || offset == CGFloat(self.collectionView.numberOfItems(inSection: 0) - 1) {
                offset = CGFloat(self.urls.count - (offset == 0 ? 0 : 1))
                scrollView.contentOffset = CGPoint(x: offset * scrollView.bounds.size.width, y: 0)
            }
            self.shufflingFigureIdentifyView.currentPage = Int(offset)
            self.beginShufflingAnimation()

    }

}
